layui.use(['layer', 'form', 'table', 'admin', 'ax', 'func','laydate'], function () {
    var $ = layui.$;
    var layer = layui.layer;
    var form = layui.form;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var func = layui.func;
    var laydate = layui.laydate;

    /**
     * 系统管理--消息管理
     */
    var Notice = {
        tableId: "yfmxTable"    //表格id
    };

    //渲染时间选择框
    // laydate.render({
    //     elem: '#timeLimit',
    //     range: true,
    //     trigger: 'click',
    //     // max: Feng.currentDate()
    // });type: 'year'

    laydate.render({
        elem: '#month',
        type: 'month'
    });

    laydate.render({
        elem: '#timeLimit',
        range: true,
        trigger: 'click',
        // max: Feng.currentDate()
    });

    __log = function(msg) {
        setTimeout(() => {
            throw new Error(msg);
        }, 0);
    }

    //监听单元格编辑
    table.on('edit(yfmxTable)', function (obj) {
        var value = obj.value //得到修改后的值
            , data = obj.data //得到所在行所有键值
            , field = obj.field; //得到字段
        // var selector = obj.tr.selector+' td[data-field="'+obj.field+'"] div';
        // var oldtext = $(selector).text();
        //__log(JSON.stringify(obj.data.gz))
        var wfgl=parseFloat(data.wfgl);//往返公里
        //油费=往返公里*0.14*6
        var yf=wfgl*0.14*6;
        data.yf=Math.round(yf);
        //维修年检保养=往返公里*0.3
        var wxnjby=wfgl*0.3;
        data.wxnjby=Math.round(wxnjby);
        if(isNaN(data.glf)){
            data.glf=0;
        }
        if(isNaN(data.wxnjby)){
            data.wxnjby=0;
        }
        // if(isNaN(data.gz)){
        //     var numArr = data.gz.match(/\d+/g);
        //     data.gz=numArr.join('');
        // }
        //
        // if(data.gz==""){
        //     data.gz=0;
        // }
        //工资字段校验
        if(field=="gz" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            table.reload(Notice.tableId);
            return false;
        }
        if(field=="wfgl" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            table.reload(Notice.tableId);
            return false;
        }
        if(field=="glf" && isNaN(value)) {
            Feng.error("修改失败，金额必须填写数字");
            table.reload(Notice.tableId);
            return false;
        }
        // 核算运费=过路+油费+工资+维修年检保养+保险+折旧
       var hsyf=parseFloat(data.glf)+parseFloat(data.yf)+parseFloat(data.gz)+parseFloat(data.wxnjby)+parseFloat(data.bx)+parseFloat(data.zj);
        data.hsyf=Math.round(hsyf);
        if(isNaN(data.hsyf)){
            data.hsyf=0;
        }

        // 运价 = 核算运费*1.12
       var yj=data.hsyf*1.12;
       data.yj=Math.round(yj);

        if(isNaN(data.yf)){
            data.yf=0;
        }
        if(isNaN(data.yj)){
            data.yj=0;
        }
        //编辑
        $.ajax({
            type: "PUT",
            url: "/yfmx/update",
            datatype: "json",
            data: data,
            success: function (data) {
                table.reload(Notice.tableId);
            }, error: function () {
                Feng.error("修改失败！");
            }, complete: function (XHR, TS) {
                //layer.close(layerIndex);
                //50秒自动刷新一次
                //setTimeout(showTime,50000);
            }

        });
        //layer.msg('[ID: '+ data.id +'] ' + field + ' 字段更改为：'+ value);
    });

    function toDecimal2(x) {
        var f = parseFloat(x);
        if (isNaN(f)) {
            return "";
        }
        var f = Math.round(x*100)/100;
        var s = f.toString();
        var rs = s.indexOf('.');
        if (rs < 0) {
            rs = s.length;
            s += '.';
        }
        while (s.length <= rs + 2) {
            s += '0';
        }
        return s;
    }

    /**
     * 获取车号
     */
    var qyAjax = new $ax(Feng.ctxPath + "/checi/cheliangList");
    var qyResult = qyAjax.start();
    $.each(qyResult, function (index, val) {
        $("#chehao").append("<option value='" + val.chehao + "'>" + val.chehao + "</option>");
    });
    form.render('select');

    var qyAjax = new $ax(Feng.ctxPath + "/checi/dmList");
    var qyResult = qyAjax.start();
    //$("#peisongMendian").html("");
    $.each(qyResult, function (index, val) {
        $("#mendian").append("<option value='" + val.dm + "'>" + val.dm + "</option>");
    });
    form.render('select');
    /**
     * 初始化表格的列
     */
    Notice.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'id', align: "center", hide: true, sort: true, title: 'id'},
            {field: 'fzr', align: "center",  title: '运输负责人',edit: 'text'},
            {field: 'rq', align: "center",  title: '日期'},
            {field: 'psxlmc', align: "center",  title: '配送线路'},
            {field: 'wfgl', align: "center", title: '往返公里', edit: 'text'},
            {field: 'glf', align: "center", title: '过路', edit: 'text'},
            {field: 'yf', align: "center",title: '油费'},
            {field: 'gz', align: "center", title: '工资',edit: 'text',},
            {field: 'wxnjby', align: "center",title: '维修年检保养'},
            {field: 'bx', align: "center", title: '保险'},
            {field: 'zj', align: "center", title: '折旧'},
            {field: 'hsyf', align: "center", title: '核算运费'},
            {field: 'yj', align: "center", title: '运价'},
            {field: 'createrName', align: "center",title: '创建人'},
            {field: 'createTime', align: "center",title: '创建时间'},
            // {align: 'center', toolbar: '#tableBar', title: '操作', minWidth: 200}
        ]];
    };

    /**
     * 点击查询按钮
     */
    Notice.search = function () {
        var queryData = {};
        queryData['timeLimit'] = $("#timeLimit").val();
        queryData['fzr'] = $("#fzr").val();
        queryData['pslx'] = $("#pslx").val();
        queryData['month'] = $("#month").val();
        table.reload(Notice.tableId, {
            where: queryData, page: {curr: 1}
        });
    };
    /**
     * 点击清空按钮
     */
    $('#btnQingkong').click(function () {
        $("#timeLimit").val("");
        $("#fzr").val("");
        $("#pslx").val("");
        $("#month").val("");
        Notice.search();
    });
    /**
     * 点击编辑
     *
     * @param data 点击按钮时候的行数据
     */
    Notice.onEditNotice = function (data) {
        func.open({
            height: 600,
            title: '修改配送车次',
            content: Feng.ctxPath + "/checi/checi_update?id=" + data.id,
            tableId: Notice.tableId
        });
    };

    /**
     * 点击删除通知
     *
     * @param data 点击按钮时候的行数据
     */
    Notice.onDeleteNotice = function (data) {
        var operation = function () {
            var ajax = new $ax(Feng.ctxPath + "/yfmx/delete", function (data) {
                Feng.success("删除成功!");
                table.reload(Notice.tableId);
            }, function (data) {
                Feng.error("删除失败!" + data.responseJSON.message + "!");
            });
            ajax.set("id", data.id);
            ajax.start();
        };
        Feng.confirm("是否删除?", operation);
    };

    /**
     * 导出excel按钮
     */
    Notice.exportExcel = function () {
        var checkRows = table.checkStatus(Notice.tableId);
        if (checkRows.data.length === 0) {
            //获取导出Excel的数据
            var ajax = new $ax(Feng.ctxPath + "/yfmx/listExport");
            var timeLimit = $("#timeLimit").val();
            var fzr = $("#fzr").val();
            var pslx = $("#pslx").val();
            var month = $("#month").val();
            ajax.set("timeLimit", timeLimit);
            ajax.set("fzr", fzr);
            ajax.set("pslx", pslx);
            ajax.set("month", month);
            var result = ajax.start();
            if(result==""){
                Feng.error("暂无数据!");
                return;
            }
            var lists = result;
            table.exportFile(tableResult.config.id, lists, 'xls');
        } else {
            table.exportFile(tableResult.config.id, checkRows.data, 'xls');
        }

    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + Notice.tableId,
        url: Feng.ctxPath + '/yfmx/list',
        page: true,
        height: "full-98",
        cellMinWidth: 100,
        cols: Notice.initColumn()
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        Notice.search();
    });

    // 添加按钮点击事件
    $('#btnAdd').click(function () {
        Notice.openAddNotice();
    });

    // 导出excel
    $('#btnExp').click(function () {
        Notice.exportExcel();
    });

    // 工具条点击事件
    table.on('tool(' + Notice.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'edit') {
            Notice.onEditNotice(data);
        } else if (layEvent === 'delete') {
            Notice.onDeleteNotice(data);
        }
    });
});
